#include "debugger.h"
#include "symbols.h"
#include "dwarf.h"
#include "disasm_objdump.h"
#include <sys/user.h>
#include <string.h>
#include <elf.h>
#include <link.h>
#include <ctype.h>
#include <math.h>

#define BREAKPOINT_CAPACITY_INIT 16

// 符号解析函数声明
static uintptr_t resolve_symbol_address(debugger_t *dbg, const char *symbol_name);

// 栈帧支持函数实现

// 获取栈回溯
stack_frame_t* debugger_get_backtrace(debugger_t *dbg) {
    if (!dbg || dbg->pid == 0) {
        printf("错误：调试器未附加到进程\n");
        return NULL;
    }

    struct user_regs_struct regs;
    if (ptrace(PTRACE_GETREGS, dbg->pid, NULL, &regs) == -1) {
        perror("ptrace GETREGS失败");
        return NULL;
    }

    stack_frame_t *head = NULL;
    stack_frame_t *current = NULL;
    
    uintptr_t rbp = (uintptr_t)regs.rbp;  // 当前帧指针
    uintptr_t rsp = (uintptr_t)regs.rsp;  // 当前栈指针
    
    int frame_count = 0;
    const int max_frames = 50;  // 最大栈帧数限制
    
    // 检查RBP是否有效（不能太小，通常栈地址较大）
    if (rbp < 0x1000) {
        // 创建当前帧（函数入口点）
        stack_frame_t *frame = malloc(sizeof(stack_frame_t));
        if (frame) {
            frame->return_address = (uintptr_t)regs.rip;
            frame->frame_pointer = rbp;
            frame->stack_pointer = rsp;
            frame->line_number = 0;
            strcpy(frame->function_name, "current_function");
            strcpy(frame->filename, "unknown");
            frame->next = NULL;
            head = frame;
        }
        return head;
    }
    
    while (rbp != 0 && frame_count < max_frames) {
        // 检查RBP是否对齐且有效
        if (rbp < 0x1000 || (rbp & 0x7) != 0) {
            break;
        }
        
        // 读取返回地址（rbp+8）
        uintptr_t return_addr = 0;
        errno = 0;
        return_addr = ptrace(PTRACE_PEEKDATA, dbg->pid, rbp + 8, NULL);
        if (errno != 0) {
            break;  // 无法读取内存，可能到达栈底
        }
        
        // 读取前一个帧指针
        uintptr_t prev_rbp = 0;
        prev_rbp = ptrace(PTRACE_PEEKDATA, dbg->pid, rbp, NULL);
        if (errno != 0) {
            break;
        }
        
        // 创建新的栈帧节点
        stack_frame_t *frame = malloc(sizeof(stack_frame_t));
        if (!frame) {
            perror("内存分配失败");
            break;
        }
        
        frame->return_address = return_addr;
        frame->frame_pointer = rbp;
        frame->stack_pointer = rsp;
        frame->next = NULL;
        
        // 尝试解析函数名和行号
        char filename[256] = "";
        unsigned int line_number = 0;
        if (debugger_find_line_by_address(dbg, return_addr, filename, sizeof(filename), &line_number) == 0) {
            strncpy(frame->filename, filename, sizeof(frame->filename) - 1);
            frame->filename[sizeof(frame->filename) - 1] = '\0';
            frame->line_number = line_number;
            
            // 从文件名提取函数名（简化实现）
            const char *basename = strrchr(filename, '/');
            if (basename) {
                basename++;  // 跳过'/'
            } else {
                basename = filename;
            }
            
            // 移除文件扩展名
            char func_name[256];
            strncpy(func_name, basename, sizeof(func_name) - 1);
            char *dot = strrchr(func_name, '.');
            if (dot) *dot = '\0';
            
            snprintf(frame->function_name, sizeof(frame->function_name), "%s", func_name);
        } else {
            // 如果无法解析源码信息，使用符号解析
            strcpy(frame->function_name, "unknown");
            strcpy(frame->filename, "unknown");
            frame->line_number = 0;
        }
        
        // 添加到链表
        if (!head) {
            head = frame;
            current = frame;
        } else {
            current->next = frame;
            current = frame;
        }
        
        // 移动到前一个栈帧
        rbp = prev_rbp;
        rsp = rbp + 16;  // 估算栈指针位置
        frame_count++;
    }
    
    return head;
}

// 释放栈回溯
void debugger_free_backtrace(stack_frame_t *backtrace) {
    stack_frame_t *current = backtrace;
    while (current) {
        stack_frame_t *next = current->next;
        free(current);
        current = next;
    }
}

// 反汇编功能实现（使用objdump）

// 反汇编指定地址的指令
int debugger_disassemble(debugger_t *dbg, uintptr_t address, size_t count) {
    if (!dbg || dbg->pid == 0) {
        printf("错误：调试器未附加到进程\n");
        return -1;
    }
    
    return disasm_address(dbg, address, count);
}

// 反汇编当前指令位置
int debugger_disassemble_current(debugger_t *dbg, size_t count) {
    if (!dbg || dbg->pid == 0) {
        printf("错误：调试器未附加到进程\n");
        return -1;
    }
    
    return disasm_current(dbg, count);
}

// 反汇编指定函数
int debugger_disassemble_function(debugger_t *dbg, const char *function_name) {
    if (!dbg || !function_name || dbg->pid == 0) {
        printf("错误：无效参数或调试器未附加到进程\n");
        return -1;
    }
    
    return disasm_function(dbg, function_name);
}

// 高级DWARF变量信息加载（使用dwarfdump精确信息）
int debugger_load_variable_info_advanced(debugger_t *dbg, const char *program_path) {
    if (!dbg || !program_path) return -1;
    
    if (dbg->dwarf_variables) {
        // 如果已经存在变量信息表，先销毁
        dwarf_variable_table_destroy(dbg->dwarf_variables);
        free(dbg->dwarf_variables);
        dbg->dwarf_variables = NULL;
    }
    
    dbg->dwarf_variables = malloc(sizeof(dwarf_variable_table_t));
    if (!dbg->dwarf_variables) return -1;
    
    // 初始化变量信息表结构
    dbg->dwarf_variables->count = 0;
    dbg->dwarf_variables->capacity = 0;
    dbg->dwarf_variables->variables = NULL;
    
    if (dwarf_load_variable_info_advanced(dbg->dwarf_variables, program_path) != 0) {
        free(dbg->dwarf_variables);
        dbg->dwarf_variables = NULL;
        printf("警告：无法加载高级变量类型信息\n");
        return -1;
    }
    
    printf("成功加载高级变量类型信息，共 %zu 个变量\n", dbg->dwarf_variables->count);
    return 0;
}

// 使用精确的DWARF信息重新加载变量类型
int debugger_reload_variable_info_with_dwarfdump(debugger_t *dbg) {
    if (!dbg || dbg->program_path[0] == '\0') {
        printf("错误：调试器未附加到程序或程序路径无效\n");
        return -1;
    }
    
    printf("正在使用dwarfdump信息重新加载变量类型...\n");
    return debugger_load_variable_info_advanced(dbg, dbg->program_path);
}

// 打印栈回溯
void debugger_print_backtrace(debugger_t *dbg) {
    stack_frame_t *backtrace = debugger_get_backtrace(dbg);
    if (!backtrace) {
        printf("无法获取栈回溯\n");
        return;
    }
    
    printf("=== 栈回溯 ===\n");
    stack_frame_t *frame = backtrace;
    int frame_num = 0;
    
    while (frame) {
        printf("#%d 0x%016lx in %s", frame_num, frame->return_address, frame->function_name);
        
        if (strcmp(frame->filename, "unknown") != 0 && frame->line_number > 0) {
            printf(" at %s:%u", frame->filename, frame->line_number);
        }
        
        printf(" (fp=0x%016lx, sp=0x%016lx)\n", frame->frame_pointer, frame->stack_pointer);
        
        frame = frame->next;
        frame_num++;
    }
    
    debugger_free_backtrace(backtrace);
}

// 获取特定帧的信息
int debugger_get_frame_info(debugger_t *dbg, int frame_index, char *function_name, size_t func_size, 
                           char *filename, size_t file_size, unsigned int *line_number) {
    if (!dbg || frame_index < 0) return -1;
    
    stack_frame_t *backtrace = debugger_get_backtrace(dbg);
    if (!backtrace) return -1;
    
    stack_frame_t *frame = backtrace;
    int current_index = 0;
    
    while (frame && current_index < frame_index) {
        frame = frame->next;
        current_index++;
    }
    
    if (!frame) {
        debugger_free_backtrace(backtrace);
        return -1;
    }
    
    if (function_name) {
        strncpy(function_name, frame->function_name, func_size - 1);
        function_name[func_size - 1] = '\0';
    }
    
    if (filename) {
        strncpy(filename, frame->filename, file_size - 1);
        filename[file_size - 1] = '\0';
    }
    
    if (line_number) {
        *line_number = frame->line_number;
    }
    
    debugger_free_backtrace(backtrace);
    return 0;
}

// 符号解析相关函数实现
uintptr_t debugger_resolve_symbol(debugger_t *dbg, const char *symbol_name) {
    return resolve_symbol_address(dbg, symbol_name);
}

int debugger_load_symbols(debugger_t *dbg, const char *program_path) {
    if (!dbg || !program_path) return -1;
    
    // 保存程序路径
    strncpy(dbg->program_path, program_path, sizeof(dbg->program_path) - 1);
    dbg->program_path[sizeof(dbg->program_path) - 1] = '\0';
    
    // 加载DWARF行号信息
    if (debugger_load_dwarf_info(dbg, program_path) == 0) {
        printf("✓ DWARF行号信息加载成功，共 %zu 条记录\n", dbg->dwarf_table->count);
        
        // 加载变量类型信息
        if (debugger_load_variable_info(dbg, program_path) == 0) {
            printf("✓ 变量类型信息加载成功，共 %zu 个变量\n", dbg->dwarf_variables->count);
        } else {
            printf("✗ 变量类型信息加载失败\n");
        }
        return 0;
    } else {
        printf("✗ DWARF行号信息加载失败\n");
        return -1;
    }
}

// 解析符号地址
static uintptr_t resolve_symbol_address(debugger_t *dbg, const char *symbol_name) {
    if (!dbg || !symbol_name || dbg->pid == 0) {
        printf("错误：无效的调试器状态或符号名\n");
        return 0;
    }
    
    // 检查进程是否仍然存活
    int status;
    pid_t result = waitpid(dbg->pid, &status, WNOHANG);
    if (result == -1) {
        perror("waitpid失败");
        printf("进程可能已经退出\n");
        return 0;
    } else if (result > 0) {
        printf("错误：进程 %d 已经退出，无法解析符号\n", dbg->pid);
        return 0;
    }
    
    // 检查程序路径是否有效
    if (dbg->program_path[0] == '\0') {
        printf("警告：无法解析符号 '%s'（附加模式下符号解析受限）\n", symbol_name);
        return 0;
    }

    // 使用精确的函数地址查找方法
    uintptr_t runtime_addr = find_function_address_in_process(dbg->pid, dbg->program_path, symbol_name);
    if (runtime_addr != 0) {
        printf("解析符号 '%s' 为地址 0x%lx\n", symbol_name, runtime_addr);
        return runtime_addr;
    }
    
    // 如果精确查找失败，回退到入口点地址
    printf("使用入口点地址 0x%lx 作为 '%s' 函数的近似\n", dbg->entry_point, symbol_name);
    return dbg->entry_point;
}

// DWARF行号映射功能实现
int debugger_load_dwarf_info(debugger_t *dbg, const char *program_path) {
    if (!dbg || !program_path) return -1;
    
    if (dbg->dwarf_table) {
        // 如果已经存在DWARF表，先销毁
        dwarf_line_table_destroy(dbg->dwarf_table);
        free(dbg->dwarf_table);
        dbg->dwarf_table = NULL;
    }
    
    dbg->dwarf_table = malloc(sizeof(dwarf_line_table_t));
    if (!dbg->dwarf_table) return -1;
    
    // 初始化DWARF表结构
    dbg->dwarf_table->count = 0;
    dbg->dwarf_table->capacity = 0;
    dbg->dwarf_table->lines = NULL;
    
    if (dwarf_load_line_info(dbg->dwarf_table, program_path) != 0) {
        free(dbg->dwarf_table);
        dbg->dwarf_table = NULL;
        printf("警告：无法加载DWARF调试信息\n");
        return -1;
    }
    
    printf("成功加载DWARF行号信息，共 %zu 条记录\n", dbg->dwarf_table->count);
    return 0;
}

uintptr_t debugger_find_address_by_line(debugger_t *dbg, const char *filename, unsigned int line) {
    if (!dbg || !dbg->dwarf_table || !filename) return 0;
    
    uintptr_t relative_addr = dwarf_find_address_by_line(dbg->dwarf_table, filename, line);
    if (relative_addr != 0) {
        printf("找到源码位置 %s:%u 对应的相对地址: 0x%lx\n", filename, line, relative_addr);
        
        // 直接使用DWARF解析的相对地址，让断点设置函数处理地址转换
        // 在实际调试中，断点设置函数会使用符号解析来获取正确的运行时地址
        return relative_addr;
    } else {
        printf("未找到源码位置 %s:%u 对应的地址\n", filename, line);
        return 0;
    }
}

int debugger_find_line_by_address(debugger_t *dbg, uintptr_t address, char *filename, size_t filename_size, unsigned int *line) {
    if (!dbg || !dbg->dwarf_table || !filename || !line) return -1;
    
    // 直接使用绝对地址进行查找
    // 在实际调试中，DWARF表应该包含运行时地址信息
    int result = dwarf_find_line_by_address(dbg->dwarf_table, address, filename, filename_size, line);
    if (result == 0) {
        printf("找到地址 0x%lx 对应的源码位置: %s:%u\n", address, filename, *line);
    } else {
        printf("未找到地址 0x%lx 对应的源码位置\n", address);
    }
    return result;
}

// 创建调试器实例
debugger_t* debugger_create(void) {
    debugger_t *dbg = malloc(sizeof(debugger_t));
    if (!dbg) return NULL;
    
    dbg->pid = 0;
    dbg->state = DEBUGGER_STOPPED;
    dbg->breakpoint_count = 0;
    dbg->breakpoint_capacity = BREAKPOINT_CAPACITY_INIT;
    dbg->program_path[0] = '\0';
    dbg->symbol_table = NULL;
    dbg->dwarf_table = NULL;
    dbg->dwarf_variables = NULL;
    
    dbg->breakpoints = malloc(sizeof(breakpoint_t) * dbg->breakpoint_capacity);
    if (!dbg->breakpoints) {
        free(dbg);
        return NULL;
    }
    
    return dbg;
}

// 销毁调试器实例
void debugger_destroy(debugger_t *dbg) {
    if (dbg) {
        if (dbg->breakpoints) {
            free(dbg->breakpoints);
        }
        if (dbg->symbol_table) {
            symbol_table_destroy(dbg->symbol_table);
        }
        if (dbg->dwarf_table) {
            dwarf_line_table_destroy(dbg->dwarf_table);
            free(dbg->dwarf_table);
        }
        free(dbg);
    }
}

// 启动新程序进行调试
int debugger_launch(debugger_t *dbg, const char *program, char *const argv[]) {
    pid_t child_pid = fork();
    
    if (child_pid == 0) {
        // 子进程：请求被跟踪
        if (ptrace(PTRACE_TRACEME, 0, NULL, NULL) == -1) {
            perror("ptrace TRACEME failed");
            exit(1);
        }
        
        // 执行目标程序
        execvp(program, argv);
        perror("execvp failed");
        exit(1);
    } else if (child_pid > 0) {
        // 父进程：设置调试器状态
        dbg->pid = child_pid;
        strncpy(dbg->program_path, program, sizeof(dbg->program_path) - 1);
        
        // 等待子进程停止
        int status;
        waitpid(child_pid, &status, 0);
        
        if (WIFSTOPPED(status)) {
            dbg->state = DEBUGGER_STOPPED;
            
            // 获取入口点地址（RIP寄存器的值）
            struct user_regs_struct regs;
            if (ptrace(PTRACE_GETREGS, dbg->pid, NULL, &regs) == 0) {
#ifdef __x86_64__
                dbg->entry_point = regs.rip;
#else
                dbg->entry_point = regs.eip;
#endif
                printf("调试器已附加到进程 %d\n", child_pid);
                printf("程序启动成功，进程已停止在入口点 0x%lx\n", dbg->entry_point);
                
                // 加载变量类型信息
                if (debugger_load_variable_info(dbg, dbg->program_path) == 0) {
                    printf("✓ 变量类型信息加载成功，共 %zu 个变量\n", dbg->dwarf_variables->count);
                } else {
                    printf("⚠ 变量类型信息加载失败，将使用符号表解析\n");
                }
                return 0;
            } else {
                perror("ptrace GETREGS failed");
                dbg->pid = 0;
                dbg->program_path[0] = '\0';
                return -1;
            }
        } else {
            printf("进程启动失败\n");
            dbg->pid = 0; // 重置PID
            dbg->program_path[0] = '\0'; // 清空程序路径
            return -1;
        }
    } else {
        perror("fork failed");
        return -1;
    }
}

// 附加到运行中的进程
int debugger_attach(debugger_t *dbg, pid_t target_pid) {
    if (ptrace(PTRACE_ATTACH, target_pid, NULL, NULL) == -1) {
        perror("ptrace ATTACH failed");
        return -1;
    }
    
    dbg->pid = target_pid;
    dbg->program_path[0] = '\0'; // 附加模式下无法确定程序路径
    
    // 等待进程停止
    int status;
    waitpid(target_pid, &status, 0);
    
    if (WIFSTOPPED(status)) {
        dbg->state = DEBUGGER_STOPPED;
        printf("调试器已附加到进程 %d\n", target_pid);
        return 0;
    } else {
        printf("附加进程失败\n");
        return -1;
    }
}

// 从进程分离
int debugger_detach(debugger_t *dbg) {
    if (dbg->pid == 0) return -1;
    
    // 恢复所有断点
    for (int i = 0; i < dbg->breakpoint_count; i++) {
        if (dbg->breakpoints[i].enabled) {
            ptrace(PTRACE_POKEDATA, dbg->pid, dbg->breakpoints[i].address, 
                   dbg->breakpoints[i].original_data);
        }
    }
    
    if (ptrace(PTRACE_DETACH, dbg->pid, NULL, NULL) == -1) {
        perror("ptrace DETACH failed");
        return -1;
    }
    
    dbg->pid = 0;
    dbg->state = DEBUGGER_STOPPED;
    printf("已从进程分离\n");
    return 0;
}

// 重新设置所有断点
static void reenable_breakpoints(debugger_t *dbg) {
    if (dbg->pid == 0) return;
    
    for (int i = 0; i < dbg->breakpoint_count; i++) {
        if (dbg->breakpoints[i].enabled) {
            // 读取当前指令
            long current_data = ptrace(PTRACE_PEEKDATA, dbg->pid, dbg->breakpoints[i].address, NULL);
            if (current_data == -1) {
                printf("警告：无法读取地址 0x%lx 的指令\n", dbg->breakpoints[i].address);
                continue;
            }
            
            // 如果当前指令不是断点指令，重新设置断点
            if ((current_data & 0xFF) != 0xCC) {
                long breakpoint_data = (current_data & ~0xFF) | 0xCC;
                if (ptrace(PTRACE_POKEDATA, dbg->pid, dbg->breakpoints[i].address, breakpoint_data) == -1) {
                    printf("警告：无法在地址 0x%lx 重新设置断点\n", dbg->breakpoints[i].address);
                }
            }
        }
    }
}

// 继续执行
int debugger_continue(debugger_t *dbg) {
    if (dbg->pid == 0) return -1;
    
    // 在继续执行前重新设置断点
    // reenable_breakpoints(dbg);
    
    if (ptrace(PTRACE_CONT, dbg->pid, NULL, NULL) == -1) {
        perror("ptrace CONT failed");
        return -1;
    }
    
    dbg->state = DEBUGGER_RUNNING;
    printf("进程继续执行\n");
    return 0;
}

// 单步执行
int debugger_step(debugger_t *dbg) {
    if (dbg->pid == 0) return -1;
    
    if (ptrace(PTRACE_SINGLESTEP, dbg->pid, NULL, NULL) == -1) {
        perror("ptrace SINGLESTEP failed");
        return -1;
    }
    
    dbg->state = DEBUGGER_STEPPING;
    printf("单步执行\n");
    return 0;
}

// 设置断点
int debugger_set_breakpoint(debugger_t *dbg, uintptr_t address) {
    if (dbg->pid == 0) return -1;
    
    // 检查断点是否已存在
    for (int i = 0; i < dbg->breakpoint_count; i++) {
        if (dbg->breakpoints[i].address == address) {
            printf("断点已存在于地址 0x%lx\n", address);
            return 0;
        }
    }
    
    // 如果地址为0，可能是通过行号设置的断点，需要特殊处理
    if (address == 0) {
        printf("错误：无效的断点地址 0x0\n");
        return -1;
    }
    
    // 扩展断点数组（如果需要）
    if (dbg->breakpoint_count >= dbg->breakpoint_capacity) {
        int new_capacity = dbg->breakpoint_capacity * 2;
        breakpoint_t *new_breakpoints = realloc(dbg->breakpoints, 
                                               sizeof(breakpoint_t) * new_capacity);
        if (!new_breakpoints) return -1;
        
        dbg->breakpoints = new_breakpoints;
        dbg->breakpoint_capacity = new_capacity;
    }
    
    // 确保进程处于停止状态
    if (dbg->state != DEBUGGER_STOPPED) {
        printf("错误：进程正在运行，无法设置断点\n");
        return -1;
    }
    
    // 读取原始指令
    errno = 0; // 清除之前的错误
    long original_data = ptrace(PTRACE_PEEKDATA, dbg->pid, address, NULL);
    if (original_data == -1) {
        printf("ptrace PEEKDATA失败: 地址 0x%lx 可能无效或不可访问\n", address);
        return -1;
    }
    
    // 设置断点（INT3指令：0xCC）
    long breakpoint_data = (original_data & ~0xFF) | 0xCC;
    if (ptrace(PTRACE_POKEDATA, dbg->pid, address, breakpoint_data) == -1) {
        perror("ptrace POKEDATA失败");
        return -1;
    }
    
    // 保存断点信息
    dbg->breakpoints[dbg->breakpoint_count].address = address;
    dbg->breakpoints[dbg->breakpoint_count].original_data = original_data;
    dbg->breakpoints[dbg->breakpoint_count].enabled = 1;
    dbg->breakpoint_count++;
    
    printf("断点设置于地址 0x%lx\n", address);
    return 0;
}

// 移除断点
int debugger_remove_breakpoint(debugger_t *dbg, uintptr_t address) {
    if (dbg->pid == 0) return -1;
    
    for (int i = 0; i < dbg->breakpoint_count; i++) {
        if (dbg->breakpoints[i].address == address && dbg->breakpoints[i].enabled) {
            // 恢复原始指令
            if (ptrace(PTRACE_POKEDATA, dbg->pid, address, 
                       dbg->breakpoints[i].original_data) == -1) {
                perror("ptrace POKEDATA failed");
                return -1;
            }
            
            dbg->breakpoints[i].enabled = 0;
            printf("断点已从地址 0x%lx 移除\n", address);
            return 0;
        }
    }
    
    printf("未找到地址 0x%lx 的断点\n", address);
    return -1;
}

// 打印寄存器状态
void debugger_print_registers(debugger_t *dbg) {
    if (dbg->pid == 0) return;
    
    struct user_regs_struct regs;
    if (ptrace(PTRACE_GETREGS, dbg->pid, NULL, &regs) == -1) {
        perror("ptrace GETREGS failed");
        return;
    }
    
    printf("=== 寄存器状态 ===\n");
#ifdef __x86_64__
    printf("RAX: 0x%016llx  RBX: 0x%016llx\n", (unsigned long long)regs.rax, (unsigned long long)regs.rbx);
    printf("RCX: 0x%016llx  RDX: 0x%016llx\n", (unsigned long long)regs.rcx, (unsigned long long)regs.rdx);
    printf("RSI: 0x%016llx  RDI: 0x%016llx\n", (unsigned long long)regs.rsi, (unsigned long long)regs.rdi);
    printf("RBP: 0x%016llx  RSP: 0x%016llx\n", (unsigned long long)regs.rbp, (unsigned long long)regs.rsp);
    printf("RIP: 0x%016llx  RFLAGS: 0x%016llx\n", (unsigned long long)regs.rip, (unsigned long long)regs.eflags);
#else
    printf("EAX: 0x%08lx  EBX: 0x%08lx\n", regs.eax, regs.ebx);
    printf("ECX: 0x%08lx  EDX: 0x%08lx\n", regs.ecx, regs.edx);
    printf("ESI: 0x%08lx  EDI: 0x%08lx\n", regs.esi, regs.edi);
    printf("EBP: 0x%08lx  ESP: 0x%08lx\n", regs.ebp, regs.esp);
    printf("EIP: 0x%08lx  EFLAGS: 0x%08lx\n", regs.eip, regs.eflags);
#endif
    printf("==================\n");
}

// 读取内存
long debugger_read_memory(debugger_t *dbg, uintptr_t address) {
    if (dbg->pid == 0) return -1;
    
    errno = 0; // 清除之前的错误
    long data = ptrace(PTRACE_PEEKDATA, dbg->pid, address, NULL);
    if (data == -1 && errno != 0) {
        perror("ptrace PEEKDATA failed");
        return -1;
    }
    
    return data;
}

// 写入内存
int debugger_write_memory(debugger_t *dbg, uintptr_t address, long data) {
    if (dbg->pid == 0) return -1;
    
    if (ptrace(PTRACE_POKEDATA, dbg->pid, address, data) == -1) {
        perror("ptrace POKEDATA failed");
        return -1;
    }
    
    return 0;
}

// 检查是否为断点触发
static int is_breakpoint_trigger(debugger_t *dbg) {
    if (dbg->pid == 0) return 0;
    
    struct user_regs_struct regs;
    if (ptrace(PTRACE_GETREGS, dbg->pid, NULL, &regs) == -1) {
        return 0;
    }
    
    // 检查RIP是否指向断点地址
    for (int i = 0; i < dbg->breakpoint_count; i++) {
        if (dbg->breakpoints[i].enabled && dbg->breakpoints[i].address == (uintptr_t)regs.rip - 1) {
            return 1;
        }
    }
    
    return 0;
}

// 处理断点触发
static void handle_breakpoint(debugger_t *dbg) {
    if (dbg->pid == 0) return;
    
    struct user_regs_struct regs;
    if (ptrace(PTRACE_GETREGS, dbg->pid, NULL, &regs) == -1) {
        perror("ptrace GETREGS failed");
        return;
    }
    
    // 查找触发的断点
    for (int i = 0; i < dbg->breakpoint_count; i++) {
        if (dbg->breakpoints[i].enabled && dbg->breakpoints[i].address == (uintptr_t)regs.rip - 1) {
            // 恢复原始指令
            if (ptrace(PTRACE_POKEDATA, dbg->pid, dbg->breakpoints[i].address, 
                       dbg->breakpoints[i].original_data) == -1) {
                perror("ptrace POKEDATA failed");
                return;
            }
            
            // 将RIP回退到断点地址
            regs.rip = dbg->breakpoints[i].address;
            if (ptrace(PTRACE_SETREGS, dbg->pid, NULL, &regs) == -1) {
                perror("ptrace SETREGS failed");
                return;
            }
            
            printf("断点触发于地址 0x%lx\n", dbg->breakpoints[i].address);
            return;
        }
    }
}

// 等待信号
void debugger_wait_for_signal(debugger_t *dbg) {
    if (dbg->pid == 0) return;
    
    int status;
    waitpid(dbg->pid, &status, 0);
    
    if (WIFEXITED(status)) {
        printf("进程已退出，状态码: %d\n", WEXITSTATUS(status));
        dbg->state = DEBUGGER_EXITED;
    } else if (WIFSTOPPED(status)) {
        int sig = WSTOPSIG(status);
        const char *sig_str = "未知信号";
        switch(sig) {
            case SIGTRAP: sig_str = "SIGTRAP (断点/单步)"; break;
            case SIGINT: sig_str = "SIGINT (中断)"; break;
            case SIGSEGV: sig_str = "SIGSEGV (段错误)"; break;
            case SIGILL: sig_str = "SIGILL (非法指令)"; break;
            case SIGFPE: sig_str = "SIGFPE (算术错误)"; break;
            case SIGBUS: sig_str = "SIGBUS (总线错误)"; break;
            default: sig_str = "其他信号"; break;
        }
        printf("进程收到信号: %d (%s)\n", sig, sig_str);
        
        // 如果是SIGTRAP信号，检查是否为断点触发
        if (sig == SIGTRAP && is_breakpoint_trigger(dbg)) {
            handle_breakpoint(dbg);
        }
        
        dbg->state = DEBUGGER_STOPPED;
    }
}

// 变量类型信息加载功能
int debugger_load_variable_info(debugger_t *dbg, const char *program_path) {
    if (!dbg || !program_path) return -1;
    
    if (dbg->dwarf_variables) {
        // 如果已经存在变量信息表，先销毁
        dwarf_variable_table_destroy(dbg->dwarf_variables);
        free(dbg->dwarf_variables);
        dbg->dwarf_variables = NULL;
    }
    
    dbg->dwarf_variables = malloc(sizeof(dwarf_variable_table_t));
    if (!dbg->dwarf_variables) return -1;
    
    // 初始化变量信息表结构
    dbg->dwarf_variables->count = 0;
    dbg->dwarf_variables->capacity = 0;
    dbg->dwarf_variables->variables = NULL;
    
    if (dwarf_load_variable_info(dbg->dwarf_variables, program_path) != 0) {
        free(dbg->dwarf_variables);
        dbg->dwarf_variables = NULL;
        printf("警告：无法加载变量类型信息\n");
        return -1;
    }
    
    printf("成功加载变量类型信息，共 %zu 个变量\n", dbg->dwarf_variables->count);
    return 0;
}

// 获取变量类型信息
dwarf_variable_info_t* debugger_get_variable_info(debugger_t *dbg, const char *variable_name) {
    if (!dbg || !variable_name || !dbg->dwarf_variables) {
        return NULL;
    }
    
    return dwarf_find_variable_by_name(dbg->dwarf_variables, variable_name);
}

// 变量地址解析功能实现（增强版，支持类型信息）

// 通过DWARF信息解析符号地址（参考dwarf_elf_parser.c逻辑）
static uintptr_t debugger_resolve_symbol_via_dwarf(debugger_t *dbg, const char *symbol_name) {
    if (!dbg || !symbol_name || dbg->program_path[0] == '\0') {
        return 0;
    }
    
    // 使用外部dwarf_elf_parser工具获取DW_OP_addr地址
    char command[1024];
    snprintf(command, sizeof(command), "./dwarf_elf_parser %s %s", dbg->program_path, symbol_name);
    
    FILE *fp = popen(command, "r");
    if (fp == NULL) {
        printf("无法执行dwarf_elf_parser工具\n");
        return 0;
    }
    
    uintptr_t addr = 0;
    char line[256];
    
    // 解析工具输出，查找地址信息
    while (fgets(line, sizeof(line), fp) != NULL) {
        // 查找包含"DW_OP_addr地址"的行
        if (strstr(line, "DW_OP_addr地址") != NULL) {
            // 解析地址值
            if (sscanf(line, "DW_OP_addr地址: 0x%lx", &addr) == 1) {
                printf("从dwarf_elf_parser工具解析到地址: 0x%lx\n", addr);
                break;
            }
        }
    }
    
    pclose(fp);
    return addr;
}

// 查找变量地址（改进实现，参考dwarf_elf_parser.c逻辑）
uintptr_t debugger_find_variable_address(debugger_t *dbg, const char *variable_name) {
    if (!dbg || !variable_name || dbg->pid == 0) {
        printf("错误：无效的调试器状态或变量名\n");
        return 0;
    }
    
    // 检查进程是否仍然存活
    int status;
    pid_t result = waitpid(dbg->pid, &status, WNOHANG);
    if (result == -1) {
        perror("waitpid失败");
        printf("进程可能已经退出\n");
        return 0;
    } else if (result > 0) {
        printf("错误：进程 %d 已经退出，无法访问变量\n", dbg->pid);
        return 0;
    }
    
    // 检查变量名是否有效
    if (strlen(variable_name) == 0 || !isalpha(variable_name[0])) {
        printf("错误：无效的变量名 '%s'\n", variable_name);
        return 0;
    }
    
    printf("正在查找变量 '%s'...\n", variable_name);
    
    // 策略1：首先尝试通过DWARF信息查找全局变量（参考dwarf_elf_parser.c）
    if (dbg->program_path[0] != '\0') {
        printf("尝试通过DWARF调试信息查找变量...\n");
        
        // 使用libdwarf直接解析DW_OP_addr地址
        uintptr_t dwarf_addr = debugger_resolve_symbol_via_dwarf(dbg, variable_name);
        if (dwarf_addr != 0) {
            printf("通过DWARF找到全局变量 '%s' 的静态地址: 0x%lx\n", variable_name, dwarf_addr);
            
            // 将静态地址转换为运行时地址（加上进程基地址）
            uintptr_t runtime_addr = dwarf_addr + dbg->base_address;
            printf("变量 '%s' 的运行时地址: 0x%lx (静态地址 0x%lx + 基地址 0x%lx)\n", 
                   variable_name, runtime_addr, dwarf_addr, dbg->base_address);
            
            // 验证地址有效性
            if (runtime_addr >= dbg->base_address && runtime_addr < dbg->base_address + 0x1000000) {
                printf("✓ 地址验证成功\n");
                
                // 更新变量信息表
                if (dbg->dwarf_variables) {
                    dwarf_variable_info_t *var_info = dwarf_find_variable_by_name(dbg->dwarf_variables, variable_name);
                    if (var_info) {
                        var_info->address = runtime_addr;
                        printf("变量类型信息: %s (类型: %s, 大小: %zu字节)\n", 
                               variable_name, var_info->type_name, var_info->size);
                    }
                }
                
                return runtime_addr;
            } else {
                printf("警告：计算出的运行时地址 0x%lx 可能无效\n", runtime_addr);
            }
        }
    }
    
    // 策略2：如果DWARF查找失败，回退到符号表查找
    printf("DWARF查找失败，尝试通过符号表查找...\n");
    uintptr_t addr = debugger_resolve_symbol(dbg, variable_name);
    if (addr != 0) {
        // 验证地址是否有效（在进程地址空间内）
        if (addr >= 0x400000 && addr < 0x800000000000) {
            printf("通过符号表找到全局变量 '%s' 的地址: 0x%lx\n", variable_name, addr);
            
            // 更新变量信息表
            if (dbg->dwarf_variables) {
                dwarf_variable_info_t *var_info = dwarf_find_variable_by_name(dbg->dwarf_variables, variable_name);
                if (var_info) {
                    var_info->address = addr;
                    printf("变量类型信息: %s (类型: %s, 大小: %zu字节)\n", 
                           variable_name, var_info->type_name, var_info->size);
                }
            }
            
            return addr;
        } else {
            printf("警告：找到的变量地址 0x%lx 可能无效\n", addr);
        }
    }
    
    // 策略3：如果全局变量查找失败，尝试查找局部变量
    printf("全局变量查找失败，尝试查找局部变量 '%s'...\n", variable_name);
    
    // 获取当前寄存器状态
    struct user_regs_struct regs;
    if (ptrace(PTRACE_GETREGS, dbg->pid, NULL, &regs) == -1) {
        perror("ptrace GETREGS失败");
        printf("无法获取寄存器状态，局部变量查找受限\n");
        return 0;
    }
    
    // 局部变量查找策略：
    // 1. 检查当前栈帧
    // 2. 遍历调用栈查找变量
    // 3. 使用DWARF调试信息（如果可用）
    
    uintptr_t stack_base = (uintptr_t)regs.rbp;
    uintptr_t stack_top = (uintptr_t)regs.rsp;
    
    printf("当前栈帧范围: RSP=0x%lx, RBP=0x%lx\n", stack_top, stack_base);
    
    if (dbg->dwarf_table) {
        printf("DWARF调试信息可用，尝试通过行号信息定位变量...\n");
        // 这里可以扩展为使用DWARF变量信息
    } else {
        printf("DWARF调试信息不可用，局部变量查找功能受限\n");
    }
    
    // 简化实现：在栈上搜索可能的变量位置
    // 注意：这是一个简化的实现，实际需要完整的调试信息支持
    printf("局部变量查找需要完整的调试信息支持\n");
    printf("当前实现主要支持全局变量和静态变量\n");
    printf("局部变量查找功能将在未来版本中完善\n");
    
    return 0;
}

// 打印变量类型信息
void debugger_print_variable_type(debugger_t *dbg, const char *variable_name) {
    if (!dbg || !variable_name) return;
    
    dwarf_variable_info_t *var_info = debugger_get_variable_info(dbg, variable_name);
    if (var_info) {
        printf("=== 变量类型信息 ===\n");
        printf("变量名: %s\n", var_info->name);
        printf("类型: %s\n", var_info->type_name);
        printf("类型代码: %d\n", var_info->type);
        printf("大小: %zu 字节\n", var_info->size);
        printf("定义位置: %s:%u\n", var_info->filename, var_info->line);
        
        if (var_info->address != 0) {
            printf("运行时地址: 0x%lx\n", var_info->address);
        } else {
            printf("运行时地址: 未确定\n");
        }
        printf("===================\n");
    } else {
        printf("无法获取变量 '%s' 的类型信息\n", variable_name);
        printf("可能的原因：\n");
        printf("  1. 变量名拼写错误\n");
        printf("  2. 程序未包含调试符号信息\n");
        printf("  3. 变量类型信息未加载\n");
    }
}

// 打印变量地址和类型信息（增强版，使用libdwarf精确类型识别）
void debugger_print_variable_address(debugger_t *dbg, const char *variable_name) {
    if (!dbg || !variable_name) return;
    
    uintptr_t addr = debugger_find_variable_address(dbg, variable_name);
    if (addr != 0) {
        printf("变量 '%s' 的内存地址: 0x%lx\n", variable_name, addr);
        
        // 使用libdwarf获取精确的类型信息
        if (dbg->program_path[0] != '\0') {
            if (dwarf_libdwarf_init(dbg->program_path) == 0) {
                char type_info[512];
                if (dwarf_get_variable_type_enhanced(variable_name, type_info, sizeof(type_info), dbg->program_path) == 0) {
                    printf("libdwarf类型信息: %s\n", type_info);
                } else {
                    printf("libdwarf: 无法获取变量 '%s' 的类型信息\n", variable_name);
                }
            } else {
                printf("libdwarf: 初始化失败\n");
            }
        }
        
        // 显示类型信息（如果可用）
        dwarf_variable_info_t *var_info = debugger_get_variable_info(dbg, variable_name);
        if(var_info == NULL){
            printf("var_info is NULL\n");
        }
        if (var_info) {
            printf("类型: %s, 大小: %zu字节\n", var_info->type_name, var_info->size);
        }
        
        // 验证地址是否可读
        if (addr < 0x1000 || addr >= 0x800000000000) {
            printf("警告：地址 0x%lx 可能无效\n", addr);
            return;
        }
        
        // 尝试读取变量的值（如果可能）
        if (dbg->state == DEBUGGER_STOPPED) {
            // 检查是否为数组类型
            int is_array = 0;
                int is_struct = 0;
            if (var_info) {
                // 检查类型代码是否为数组类型
                if (var_info->type == DWARF_TYPE_ARRAY) {
                    is_array = 1;
                }
                // 检查类型名中是否包含数组标识符
                else if (strstr(var_info->type_name, "[") != NULL || 
                         strstr(var_info->type_name, "array") != NULL ||
                         strstr(var_info->type_name, "数组") != NULL) {
                    is_array = 1;
                }
            }
            
            // 特殊处理：根据libdwarf类型信息识别字符数组和结构体
            if (!is_array && !is_struct && dbg->program_path[0] != '\0') {
                if (dwarf_libdwarf_init(dbg->program_path) == 0) {
                    char type_info[512];
                    if (dwarf_get_variable_type_enhanced(variable_name, type_info, sizeof(type_info), dbg->program_path) == 0) {
                        // 如果libdwarf识别为字符数组，则按数组处理
                        if (strstr(type_info, "char[]") != NULL || 
                            (strstr(type_info, "char") != NULL && strstr(type_info, "[") != NULL)) {
                            is_array = 1;
                            printf("libdwarf识别为字符数组，按数组处理\n");
                        }
                        // 如果libdwarf识别为结构体，则按结构体处理
                        else if (strstr(type_info, "struct") != NULL || 
                                 strstr(type_info, "test_struct") != NULL) {
                            is_struct = 1;
                            printf("libdwarf识别为结构体，按结构体处理\n");
                            
                            // 如果变量信息表中有错误的类型信息，使用libdwarf的正确信息
                            if (var_info && strstr(type_info, "test_struct") != NULL) {
                                strcpy(var_info->type_name, "test_struct");
                                var_info->size = 40; // test_struct的大小为40字节
                                var_info->type = DWARF_TYPE_STRUCT;
                            }
                        }
                    }
                }
            }
            
            // 对于结构体类型，显示结构体成员信息
            if (is_struct) {
                printf("结构体类型变量，显示成员信息:\n");
                
                // 根据结构体类型名进行特殊处理
                if (strstr(var_info->type_name, "test_struct") != NULL) {
                    printf("  结构体类型: test_struct\n");
                    printf("  结构体大小: %zu字节\n", var_info->size);
                    
                    // 解析test_struct的成员
                    // id: 偏移0, 大小4字节
                    long id_value = debugger_read_memory(dbg, addr);
                    if (id_value != -1) {
                        printf("  id: %d\n", (int)id_value);
                    }
                    
                    // value: 偏移4, 大小4字节  
                    long value_data = debugger_read_memory(dbg, addr + 4);
                    if (value_data != -1) {
                        float float_value;
                        memcpy(&float_value, &value_data, sizeof(float));
                        printf("  value: %f\n", float_value);
                    }
                    
                    // name: 偏移8, 大小32字节
                    printf("  name: \"");
                    for (int i = 0; i < 32; i++) {
                        long char_data = debugger_read_memory(dbg, addr + 8 + i);
                        if (char_data != -1) {
                            char ch = (char)(char_data & 0xFF);
                            if (ch == '\0') break;
                            if (isprint(ch)) {
                                printf("%c", ch);
                            } else {
                                printf("\\x%02x", (unsigned char)ch);
                            }
                        } else {
                            break;
                        }
                    }
                    printf("\"\n");
                } else {
                    printf("  未知结构体类型: %s\n", var_info->type_name);
                    printf("  结构体大小: %zu字节\n", var_info->size);
                    printf("  显示原始内存内容:\n");
                    
                    // 显示结构体的原始内存内容
                    for (size_t i = 0; i < var_info->size; i += sizeof(long)) {
                        long data = debugger_read_memory(dbg, addr + i);
                        if (data != -1) {
                            printf("    [偏移%zu]: 0x%lx\n", i, data);
                        } else {
                            printf("    [偏移%zu]: 读取失败\n", i);
                            break;
                        }
                    }
                }
            }
            // 对于数组类型，显示数组信息并读取所有元素
            else if (is_array) {
                printf("数组类型变量，显示数组内容:\n");
                
                // 获取数组大小信息
                int array_size = 5; // 默认大小，从类型信息中解析
                if (var_info) {
                    // 从类型名中解析数组大小，例如 "int[5]"
                    const char *bracket = strchr(var_info->type_name, '[');
                    if (bracket) {
                        array_size = atoi(bracket + 1);
                        if (array_size <= 0) array_size = 5; // 默认值
                    }
                    
                    // 特殊处理：对于字符数组，如果类型名是char*但实际是数组，使用默认大小
                    if (strcmp(var_info->type_name, "char*") == 0 && 
                        (strstr(variable_name, "string") != NULL || strstr(variable_name, "str") != NULL)) {
                        array_size = 32; // 默认字符串长度
                    }
                }
                
                printf("  数组大小: %d 个元素\n", array_size);
                
                // 读取数组的所有元素 - 根据变量类型确定元素大小
                int elements_read = 0;
                size_t element_size = sizeof(int); // 默认元素大小
                
                // 根据变量类型信息确定元素大小
                if (var_info) {
                    // 从类型名中推断元素类型
                    if (strstr(var_info->type_name, "char") != NULL) {
                        element_size = sizeof(char);
                    } else if (strstr(var_info->type_name, "short") != NULL) {
                        element_size = sizeof(short);
                    } else if (strstr(var_info->type_name, "int") != NULL) {
                        element_size = sizeof(int);
                    } else if (strstr(var_info->type_name, "long") != NULL) {
                        element_size = sizeof(long);
                    } else if (strstr(var_info->type_name, "float") != NULL) {
                        element_size = sizeof(float);
                    } else if (strstr(var_info->type_name, "double") != NULL) {
                        element_size = sizeof(double);
                    }
                }
                
                printf("  元素大小: %zu 字节\n", element_size);
                
                // 安全地读取数组元素，避免段错误
                printf("  数组元素: [");
                
                // 逐个读取数组元素
                for (int i = 0; i < array_size; i++) {
                    uintptr_t element_addr = addr + (i * element_size);
                    long element_value = 0;
                    
                    // 使用ptrace安全读取内存，检查地址有效性
                    if (element_addr == 0) {
                        printf("?");
                    } else {
                        errno = 0;
                        element_value = ptrace(PTRACE_PEEKDATA, dbg->pid, (void*)element_addr, NULL);
                        
                        if (errno != 0 || element_value == -1) {
                            // 读取失败，显示占位符
                            printf("?");
                        } else {
                            // 根据元素类型显示值
                            if (element_size == sizeof(char)) {
                                // 对于字符类型，显示字符本身而不是ASCII码
                                char ch = (char)element_value;
                                if (ch >= 32 && ch <= 126) {
                                    printf("'%c'", ch);
                                } else {
                                    printf("%d", ch);
                                }
                            } else if (element_size == sizeof(short)) {
                                printf("%d", (short)element_value);
                            } else if (element_size == sizeof(int)) {
                                printf("%d", (int)element_value);
                            } else if (element_size == sizeof(long)) {
                                printf("%ld", element_value);
                            } else {
                                printf("%ld", element_value);
                            }
                        }
                    }
                    
                    if (i < array_size - 1) {
                        printf(", ");
                    }
                }
                
                printf("]\n");
                
                // 验证数组地址是否有效
                if (addr < 0x1000 || addr >= 0x800000000000) {
                    printf("  警告：数组地址 0x%lx 可能无效\n", addr);
                    return;
                }
                
                for (int i = 0; i < array_size; i++) {
                    uintptr_t element_addr = addr + i * element_size;
                    
                    // 验证元素地址是否在合理范围内
                    if (element_addr < 0x1000 || element_addr >= 0x800000000000) {
                        printf("  [%d] = <地址无效: 0x%lx>\n", i, element_addr);
                        continue;
                    }
                    
                    errno = 0; // 清除错误状态
                    long data = debugger_read_memory(dbg, element_addr);
                    if (data != -1 && errno == 0) {
                        // 根据元素类型正确显示值
                        if (element_size == sizeof(char)) {
                            char ch = (char)data;
                            if (ch >= 32 && ch <= 126) {
                                printf("  [%d] = '%c' (ASCII: %d, 0x%lx)\n", i, ch, ch, data);
                            } else {
                                printf("  [%d] = %d (0x%lx)\n", i, ch, data);
                            }
                        } else if (element_size == sizeof(short)) {
                            printf("  [%d] = %d (0x%lx)\n", i, (short)data, data);
                        } else if (element_size == sizeof(int)) {
                            printf("  [%d] = %d (0x%lx)\n", i, (int32_t)data, data);
                        } else if (element_size == sizeof(long)) {
                            printf("  [%d] = %ld (0x%lx)\n", i, (int64_t)data, data);
                        } else {
                            printf("  [%d] = 0x%lx\n", i, data);
                        }
                        elements_read++;
                    } else {
                        printf("  [%d] = <无法读取>", i);
                        if (errno != 0) {
                            printf(" (错误: %s)", strerror(errno));
                        }
                        printf("\n");
                        // 如果连续多个元素无法读取，停止继续读取
                        if (i > 0 && elements_read == 0) {
                            break;
                        }
                    }
                }
                
                if (elements_read == 0) {
                    printf("  警告：无法读取任何数组元素\n");
                }
            } else {
                // 对于非数组类型，使用原来的读取逻辑
                size_t read_size = 4; // 默认4字节（int大小）
                if (var_info) {
                    read_size = var_info->size;
                }
                
                // 安全的内存读取，避免越界
                if (read_size > 8) read_size = 8; // 限制最大读取8字节
                
                // 读取变量值 - 使用正确的内存读取方式
                uint64_t value = 0;
                int valid_read = 1;
                
                // 按机器字长读取，而不是按字节读取
                size_t words_to_read = (read_size + sizeof(long) - 1) / sizeof(long);
                
                for (size_t i = 0; i < words_to_read; i++) {
                    long data = debugger_read_memory(dbg, addr + i * sizeof(long));
                    if (data == -1) {
                        valid_read = 0;
                        break;
                    }
                    // 合并读取的数据
                    value |= ((uint64_t)data << (i * sizeof(long) * 8));
                }
            
                if (valid_read) {
                    printf("变量 '%s' 的原始值: 0x%lx\n", variable_name, value);
                    
                    // 根据类型信息进行精确的值解释
                    if (var_info) {
                        switch (var_info->type) {
                            case DWARF_TYPE_INT:
                                if (read_size == 4) {
                                    printf("整数值: %d\n", (int32_t)value);
                                } else if (read_size == 8) {
                                    printf("长整数值: %ld\n", (int64_t)value);
                                } else {
                                    printf("整数值: %d (截断)\n", (int32_t)value);
                                }
                                break;
                                
                            case DWARF_TYPE_CHAR:
                                printf("字符值: '%c' (ASCII %d)\n", (char)(value & 0xFF), (int)(value & 0xFF));
                                break;
                                
                            case DWARF_TYPE_FLOAT:
                                if (read_size == 4) {
                                    float float_value;
                                    memcpy(&float_value, &value, sizeof(float));
                                    printf("浮点值: %f\n", float_value);
                                } else {
                                    printf("浮点类型但大小不匹配: %zu字节\n", read_size);
                                }
                                break;
                                
                            case DWARF_TYPE_DOUBLE:
                                if (read_size == 8) {
                                    double double_value;
                                    memcpy(&double_value, &value, sizeof(double));
                                    printf("双精度值: %f\n", double_value);
                                } else {
                                    printf("双精度类型但大小不匹配: %zu字节\n", read_size);
                                }
                                break;
                                
                            case DWARF_TYPE_POINTER:
                                printf("指针值: 0x%lx\n", (uintptr_t)value);
                                break;
                                
                            default:
                                printf("未知类型，显示原始值\n");
                                break;
                        }
                    } else {
                        // 没有类型信息时的智能推断
                        printf("智能类型推断:\n");
                        
                        // 1. 检查是否为小整数
                        if (value <= 0x7FFFFFFF) {
                            printf("  可能为整数: %ld\n", (int64_t)value);
                            if (value <= 127) {
                                printf("  可能为字符: '%c'\n", (char)value);
                            }
                        }
                        
                        // 2. 检查是否为指针
                        if (value >= 0x400000 && value < 0x800000000000) {
                            printf("  可能为指针: 0x%lx\n", value);
                            
                            // 尝试读取指针指向的内容（字符串）
                            char buffer[32] = {0};
                            int valid_string = 1;
                            for (int i = 0; i < 31; i++) {
                                long char_data = debugger_read_memory(dbg, value + i);
                                if (char_data == -1) {
                                    valid_string = 0;
                                    break;
                                }
                                char c = (char)(char_data & 0xFF);
                                if (c == 0) {
                                    buffer[i] = '\0';
                                    break;
                                } else if (c >= 32 && c <= 126) {
                                    buffer[i] = c;
                                } else {
                                    valid_string = 0;
                                    break;
                                }
                            }
                            
                            if (valid_string && strlen(buffer) > 0) {
                                printf("  指向字符串: \"%s\"\n", buffer);
                            }
                        }
                        
                        // 3. 检查是否为字符串常量（直接内联的字符串）
                        uint64_t test_value = value;
                        char str_buffer[9] = {0};
                        int has_printable = 0;
                        
                        for (int i = 0; i < 8; i++) {
                            char c = (char)((test_value >> (i * 8)) & 0xFF);
                            if (c >= 32 && c <= 126) {
                                str_buffer[i] = c;
                                has_printable = 1;
                            } else if (c == 0) {
                                str_buffer[i] = '\0';
                                break;
                            } else {
                                break;
                            }
                        }
                        
                        if (has_printable) {
                            str_buffer[8] = '\0';
                            printf("  可能为内联字符串: \"%s\"\n", str_buffer);
                        }
                        
                        // 4. 检查是否为浮点数模式
                        uint32_t float_bits = value & 0xFFFFFFFF;
                        if ((float_bits & 0x7F800000) == 0x7F800000) { // NaN/Inf模式
                            printf("  可能为特殊浮点数\n");
                        }
                    }
                } else {
                    printf("无法读取变量值\n");
                }
            }
        } else {
            printf("无法读取变量 '%s' 的值（地址可能无效）\n", variable_name);
        }
    } else {
        printf("进程正在运行，无法读取变量值\n");
    }
}

// 显示进程内存映射信息
int debugger_print_proc_maps(debugger_t *dbg) {
    if (!dbg || dbg->pid == 0) {
        printf("错误：调试器未附加到进程\n");
        return -1;
    }
    
    char maps_path[256];
    snprintf(maps_path, sizeof(maps_path), "/proc/%d/maps", dbg->pid);
    
    FILE *maps_file = fopen(maps_path, "r");
    if (!maps_file) {
        perror("无法打开/proc/pid/maps文件");
        return -1;
    }
    
    printf("\n=== 进程 %d 内存映射信息 ===\n", dbg->pid);
    printf("----------------------------------------------------------------------------------------\n");
    
    char line[1024];
    int entry_count = 0;
    
    while (fgets(line, sizeof(line), maps_file)) {
        printf("%s", line);
        entry_count++;
    }
    
    fclose(maps_file);
    printf("=== 共 %d 个内存映射区域 ===\n", entry_count);
    return 0;
}